import {
  reqCode,
  reqLogin,
  reqRegisterUser,
  reqUserInfo,
  reqLogout,
} from "@/api";
import { setToken, getToken, removeToken } from "@/utils";
export default {
  state: {
    code: "", //验证码
    token: getToken(), //用户的真正信息
    userInfo: {},
  },
  mutations: {
    UPDATE_CODE(state, code) {
      state.code = code;
    },
    UPDATE_TOKEN(state, token) {
      state.token = token;
    },
    UPDATE_USERINFO(state, userInfo) {
      state.userInfo = userInfo;
    },
    REMOVE_USERABOUT(state) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
  },
  actions: {
    // 获取验证码
    async getCode({ commit }, phone) {
      // 把接收来的phone 传给api，然后res接收值
      const res = await reqCode(phone);
      if (res.code === 200) {
        // 触发这个方法，然后传值给他
        commit("UPDATE_CODE", res.data);
        return "ok";
      } else {
        return Promise.reject("misson");
      }
    },
    // 用户注册
    async getRegisterUser({ commit }, paramsObj) {
      const res = await reqRegisterUser(paramsObj);
      if (res.code === 200) {
        return "ok";
      } else {
        return Promise.reject("misson");
      }
    },
    // 用户登录
    async getLogin({ commit }, paramsObj) {
      console.log(123456);
      const res = await reqLogin(paramsObj);
      if (res.code === 200) {
        commit("UPDATE_TOKEN", res.data.token);
        console.log(res);
        setToken(res.data.token);
        return "ok";
      } else {
        return Promise.reject("misson");
      }
    },
    // 用户信息
    async getUserInfo({ commit }) {
      const res = await reqUserInfo();
      if (res.code === 200) {
        commit("UPDATE_USERINFO", res.data);
        return "ok";
      } else {
        return Promise.reject("user");
      }
    },
    async getLogout({ commit }) {
      const res = await reqLogout();
      if (res.code === 200) {
        commit("REMOVE_USERABOUT");
        return "ok";
      } else {
        return Promise.reject("user");
      }
    },
  },
  getters: {},
};
